#include "do_fork.h"
#include "mm.h"
#include "task.h"
#include "asm/processor.h"

static void active_task(struct task_struct* p) {
    p->state = TASK_RUNNING;
    // list_add_to_behind(&rq.list_entry, &p->list_entry);
    list_add_to_behind(&init_task.list_entry, &p->list_entry);
}

u64 do_fork(u64 clone_flags, u64 fn, u64 arg) {

    int new_pid = find_empty_task();
    task_union* new_task_union = (task_union*)PhyToVirt(alloc_one_page());
    struct task_struct* new_task_struct = &(new_task_union->tsk);

    new_task_struct->counter = 100;
    new_task_struct->flags = PF_KTHREAD;
    new_task_struct->need_resched = 0;
    new_task_struct->pid = new_pid;
    new_task_struct->preempt_count = 0;
    new_task_struct->priority = 0;
    // new_task_struct->state = TASK_RUNNING;

    cpu_context* cpu_contextp = &new_task_struct->run_context;
    cpu_contextp->pc = fn;
    cpu_contextp->sp = (u64)new_task_struct+THREAD_SIZE-8;

    active_task(new_task_struct);

    return new_pid;
}


